// pages/JX/index/index.js
import S_request from '../../../utils/requestService.js';
import CONFIG from '../../../config.js';
import * as utils from '../../../utils/util.js';

const loginUrl = require('../../../config').loginUrl;
const app = getApp()
let navToUrl = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bannerList: null, //轮播图
    indicatorDots: true, //是否显示面板指示点
    autoplay: false, //是否自动切换
    interval: 3000, //自动切换时间间隔,3s
    duration: 500, //  滑动动画时长1s
    circular: true, //是否采用衔接滑动
    preMargin: '40rpx',
    nextMargin: '40rpx',
    swiperCurrent: 0, //当前的位置
    isShowLogin: false,
    userId: '-1', //记录分享的人, -1没有读取到用户id
    treasure_id: '-2', //-2：不是分享进入， -1：其他分享  其他：详情页分享
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let url = decodeURIComponent(options.url)
    if (url && url != 'undefined' && url != '') {
      navToUrl = url;
    }
    let userId = options.fu;
    if (userId && userId != 'undefined' && userId != '') {
      this.setData({
        userId: userId
      })
    }
    let treasure_id = options.treasure_id;
    if (treasure_id && treasure_id != 'undefined' && treasure_id != '') {
      this.setData({
        treasure_id: treasure_id
      })
    }
    console.log("userId===" + this.data.userId + "treasure_id===" + treasure_id)
    this.checkLogin();
  },
  getJXLists: function() {
    S_request.jx.getJXList(this.data.userId, this.data.treasure_id, (result) => {
      if (result.lists == null || result.lists.length == 0) return;
      for (let i = 0; i < result.lists.length; i++) {
        let item = result.lists[i];
        item.open_time = utils.formatTime(item.open_time, 3);
        //pay_status表示类型 0：系统随机 1：分享最多者获得
        //join表示自己是否参与 0：未参与抽奖 1：已参与
        if (item.pay_status == 0) {
          item.txt = '系统随机抽取'
        } else {
          item.txt = '邀请最多者获得'
        }
      }
      // let count = wx.getStorageSync('list_count');
      // if (count != result.lists.length) {
      //   wx.setStorageSync('list_count', result.lists.length);
      //   this.setData({
      //     swiperCurrent: 0
      //   })
      // }
      this.setData({
        swiperCurrent: 0,
        bannerList: result.lists
      })
    })
  },
  toDetail: function(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../detail/detail?id=' + id,
    })
  },
  modalLoginRightAc: function() {

  },
  checkLogin: function() {
    let self = this;
    this.checkSession((isShiXiao) => {
      console.log('isShiXiao==' + isShiXiao)
      this.getUserToken(isShiXiao, function(err) {
        if (!err) {
          if (navToUrl != '') {
            console.log("navToUrl===" + navToUrl)
            wx.navigateTo({
              url: navToUrl
            })
          }
          self.getJXLists();
        }
      })
    })
  },
  checkSession: function(callback) {
    //校验session_key是否有效，从而避免小程序反复执行登录流程
    let isShiXiao = false;
    wx.checkSession({
      success: res => {
        //session_key 未过期，并且在本生命周期一直有效
        console.log("session_key 未过期")
        isShiXiao = false;
        callback(isShiXiao)
      },
      fail: res => {
        // session_key 已经失效，需要重新执行登录流程
        console.log("session_key 已经失效")
        isShiXiao = true;
        callback(isShiXiao)
      }
    })
  },
  getUserToken: function(isShiXiao, callback) {
    var self = this;
    let token = wx.getStorageSync("token");
    if (!isShiXiao && token) {
      callback(null);
    } else {
      // 登录
      wx.login({
        success: function(data) {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          console.log("login11122====" + JSON.stringify(data));
          S_request.login(data.code, (result) => {
            callback(result)
          })
        },
        fail: function(err) {
          console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
          callback(err)
        }
      })
    }
  },
  toSY: function() {
    wx.navigateTo({
      url: '../shouye/shouye',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getJXLists();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: false,
      success: function() {}
    });
    let obj = { 'pagepath': CONFIG.SHARE.path }
    S_request.jx.recordShare("-1", obj);
    return {
      title: CONFIG.SHARE.title,
      path: CONFIG.SHARE.path,
      imageUrl: CONFIG.SHARE.imageUrl,
      success: (res) => { //新版不走回调
        console.log("分享成功")
      }
    }
  },
  formSubmit: function(e) {
    let formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)
    let id = e.currentTarget.dataset.id;
    console.log("jx id==" + id + ",formId===" + formId)
    let param = 'formId=' + formId;
    S_request.jx.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
  }
})